package notes.java.nio.demo;

import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.Pipe.SinkChannel;
import java.nio.channels.Pipe.SourceChannel;

import org.junit.Test;

/**
 * 测试管道
 *管道：两个线程之间的单向数据连接
 */
public class N5_TestPipe {

	@Test
	public void testPipe() throws Exception {
		// 1、获取管道
		Pipe pipe = Pipe.open();
		
		// 2、获取管道的输入通道
		SinkChannel sinkChannel = pipe.sink();
		
		// 3、分配缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(1024); 
		buffer.put("你好啊".getBytes());
		buffer.flip();
		
		// 4、写入管道
		sinkChannel.write(buffer);
		
		// 5、获取输出的管道的通道
		SourceChannel sourceChannel = pipe.source();
		buffer.flip();
		sourceChannel.read(buffer);
		
		System.out.println(new String(buffer.array()));
		
		sinkChannel.close();
		sourceChannel.close();
	}
}
